import QtQuick 2.14
import QtQuick.Controls 2.14
import QtQuick.Layouts 1.14

Item {
    id: auditTrailPage
    
    property var qmlBridge
    
    Rectangle {
        anchors.fill: parent
        color: "#f5f5f5"
        
        ColumnLayout {
            anchors.fill: parent
            anchors.margins: 20
            spacing: 20
            
            // Header
            Rectangle {
                Layout.fillWidth: true
                Layout.preferredHeight: 60
                color: "#9C27B0"
                radius: 8
                
                RowLayout {
                    anchors.fill: parent
                    anchors.margins: 20
                    
                    Text {
                        text: "Audit Trail"
                        font.pixelSize: 20
                        font.bold: true
                        color: "white"
                    }
                    
                    Item { Layout.fillWidth: true }
                    
                    Button {
                        text: "Export Audit Log"
                        onClicked: {
                            if (qmlBridge) {
                                var filePath = "audit_export_" + Qt.formatDateTime(new Date(), "yyyyMMdd_hhmmss") + ".csv"
                                if (qmlBridge.exportAuditLogs(filePath, "csv")) {
                                    console.log("Audit log exported successfully to:", filePath)
                                } else {
                                    console.log("Failed to export audit log")
                                }
                            }
                        }
                    }
                    
                    Button {
                        text: "Refresh"
                        onClicked: refreshAuditData()
                    }
                }
            }
            
            // Filter Controls
            Rectangle {
                Layout.fillWidth: true
                Layout.preferredHeight: 80
                color: "white"
                radius: 8
                border.color: "#e0e0e0"
                border.width: 1
                
                RowLayout {
                    anchors.fill: parent
                    anchors.margins: 15
                    spacing: 20
                    
                    Text {
                        text: "Filter:"
                        font.bold: true
                    }
                    
                    ComboBox {
                        id: actionFilter
                        model: ["All Actions", "Login", "Logout", "Create", "Update", "Delete", "System"]
                        currentIndex: 0
                        onCurrentTextChanged: filterAuditData()
                    }
                    
                    Text {
                        text: "User:"
                    }
                    
                    ComboBox {
                        id: userFilter
                        model: ["All Users", "admin", "operator", "system"]
                        currentIndex: 0
                        onCurrentTextChanged: filterAuditData()
                    }
                    
                    Text {
                        text: "Date:"
                    }
                    
                    TextField {
                        id: dateFilter
                        placeholderText: "YYYY-MM-DD"
                        onTextChanged: filterAuditData()
                    }
                    
                    Item { Layout.fillWidth: true }
                    
                    Text {
                        text: "Total Records: " + auditListModel.count
                        color: "#666"
                    }
                }
            }
            
            // Audit Records List
            Rectangle {
                Layout.fillWidth: true
                Layout.fillHeight: true
                color: "white"
                radius: 8
                border.color: "#e0e0e0"
                border.width: 1
                
                ColumnLayout {
                    anchors.fill: parent
                    anchors.margins: 20
                    spacing: 15
                    
                    // Table Header
                    Rectangle {
                        Layout.fillWidth: true
                        Layout.preferredHeight: 40
                        color: "#f5f5f5"
                        border.color: "#e0e0e0"
                        border.width: 1
                        
                        RowLayout {
                            anchors.fill: parent
                            anchors.margins: 10
                            spacing: 10
                            
                            Text {
                                Layout.preferredWidth: 150
                                text: "Timestamp"
                                font.bold: true
                                color: "#333"
                            }
                            
                            Text {
                                Layout.preferredWidth: 100
                                text: "User"
                                font.bold: true
                                color: "#333"
                            }
                            
                            Text {
                                Layout.preferredWidth: 100
                                text: "Action"
                                font.bold: true
                                color: "#333"
                            }
                            
                            Text {
                                Layout.preferredWidth: 120
                                text: "Table/Object"
                                font.bold: true
                                color: "#333"
                            }
                            
                            Text {
                                Layout.fillWidth: true
                                text: "Description"
                                font.bold: true
                                color: "#333"
                            }
                        }
                    }
                    
                    // Audit Records ListView
                    ListView {
                        Layout.fillWidth: true
                        Layout.fillHeight: true
                        model: auditListModel
                        delegate: auditDelegate
                        
                        ScrollBar.vertical: ScrollBar {}
                    }
                }
            }
        }
    }
    
    // Audit List Model
    ListModel {
        id: auditListModel
        
        Component.onCompleted: {
            loadAuditData()
        }
    }
    
    // Audit Delegate
    Component {
        id: auditDelegate
        
        Rectangle {
            width: ListView.view.width
            height: 60
            color: index % 2 === 0 ? "#f9f9f9" : "white"
            border.color: "#e0e0e0"
            border.width: 1
            
            RowLayout {
                anchors.fill: parent
                anchors.margins: 10
                spacing: 10
                
                Text {
                    Layout.preferredWidth: 150
                    text: timestamp
                    font.pixelSize: 12
                    color: "#333"
                    wrapMode: Text.WordWrap
                }
                
                Text {
                    Layout.preferredWidth: 100
                    text: userId
                    font.pixelSize: 12
                    color: "#666"
                    wrapMode: Text.WordWrap
                }
                
                Rectangle {
                    Layout.preferredWidth: 100
                    height: 25
                    color: getActionColor(action)
                    radius: 12
                    
                    function getActionColor(action) {
                        switch(action) {
                            case "Login": return "#4CAF50"
                            case "Logout": return "#FF9800"
                            case "Create": return "#2196F3"
                            case "Update": return "#9C27B0"
                            case "Delete": return "#F44336"
                            case "System": return "#607D8B"
                            default: return "#9E9E9E"
                        }
                    }
                    
                    function getActionText(action) {
                        return action || "Unknown"
                    }
                    
                    Text {
                        anchors.centerIn: parent
                        text: parent.getActionText(action)
                        color: "white"
                        font.pixelSize: 10
                        font.bold: true
                    }
                }
                
                Text {
                    Layout.preferredWidth: 120
                    text: tableName
                    font.pixelSize: 12
                    color: "#666"
                    wrapMode: Text.WordWrap
                }
                
                Text {
                    Layout.fillWidth: true
                    text: description
                    font.pixelSize: 12
                    color: "#333"
                    wrapMode: Text.WordWrap
                }
                
                Button {
                    Layout.preferredWidth: 60
                    text: "Details"
                    onClicked: showAuditDetails(index)
                }
            }
        }
    }
    
    // Audit Details Dialog
    Dialog {
        id: auditDetailsDialog
        title: "Audit Record Details"
        width: 600
        height: 400
        anchors.centerIn: parent
        modal: true
        
        property var currentRecord: null
        
        ScrollView {
            anchors.fill: parent
            
            ColumnLayout {
                width: auditDetailsDialog.width - 40
                spacing: 15
                
                GridLayout {
                    Layout.fillWidth: true
                    columns: 2
                    columnSpacing: 20
                    rowSpacing: 10
                    
                    Text { text: "Timestamp:"; font.bold: true }
                    Text { text: auditDetailsDialog.currentRecord ? auditDetailsDialog.currentRecord.timestamp : "" }
                    
                    Text { text: "User ID:"; font.bold: true }
                    Text { text: auditDetailsDialog.currentRecord ? auditDetailsDialog.currentRecord.userId : "" }
                    
                    Text { text: "Action:"; font.bold: true }
                    Text { text: auditDetailsDialog.currentRecord ? auditDetailsDialog.currentRecord.action : "" }
                    
                    Text { text: "Table/Object:"; font.bold: true }
                    Text { text: auditDetailsDialog.currentRecord ? auditDetailsDialog.currentRecord.tableName : "" }
                    
                    Text { text: "Record ID:"; font.bold: true }
                    Text { text: auditDetailsDialog.currentRecord ? auditDetailsDialog.currentRecord.recordId : "" }
                }
                
                Rectangle {
                    Layout.fillWidth: true
                    height: 1
                    color: "#e0e0e0"
                }
                
                Text {
                    text: "Description:"
                    font.bold: true
                }
                
                Rectangle {
                    Layout.fillWidth: true
                    Layout.preferredHeight: 60
                    color: "#f9f9f9"
                    border.color: "#e0e0e0"
                    border.width: 1
                    
                    ScrollView {
                        anchors.fill: parent
                        anchors.margins: 10
                        
                        Text {
                            text: auditDetailsDialog.currentRecord ? auditDetailsDialog.currentRecord.description : ""
                            wrapMode: Text.WordWrap
                            width: parent.width
                        }
                    }
                }
                
                Text {
                    text: "Old Value:"
                    font.bold: true
                }
                
                Rectangle {
                    Layout.fillWidth: true
                    Layout.preferredHeight: 60
                    color: "#ffebee"
                    border.color: "#e0e0e0"
                    border.width: 1
                    
                    ScrollView {
                        anchors.fill: parent
                        anchors.margins: 10
                        
                        Text {
                            text: auditDetailsDialog.currentRecord ? auditDetailsDialog.currentRecord.oldValue : ""
                            wrapMode: Text.WordWrap
                            width: parent.width
                            color: "#d32f2f"
                        }
                    }
                }
                
                Text {
                    text: "New Value:"
                    font.bold: true
                }
                
                Rectangle {
                    Layout.fillWidth: true
                    Layout.preferredHeight: 60
                    color: "#e8f5e8"
                    border.color: "#e0e0e0"
                    border.width: 1
                    
                    ScrollView {
                        anchors.fill: parent
                        anchors.margins: 10
                        
                        Text {
                            text: auditDetailsDialog.currentRecord ? auditDetailsDialog.currentRecord.newValue : ""
                            wrapMode: Text.WordWrap
                            width: parent.width
                            color: "#388e3c"
                        }
                    }
                }
            }
        }
    }
    
    // Functions
    function loadAuditData() {
        auditListModel.clear()
        
        if (qmlBridge) {
            // Get audit logs from the real audit system
            var auditData = qmlBridge.getAuditLogs("", "", "", "")
            
            for (var i = 0; i < auditData.length; i++) {
                var record = auditData[i]
                auditListModel.append({
                    timestamp: record.timestamp || "",
                    userId: record.userId || "",
                    action: getActionString(record.action) || "Unknown",
                    tableName: record.tableName || "",
                    recordId: record.recordId || "",
                    oldValue: record.oldValue || "",
                    newValue: record.newValue || "",
                    description: record.description || ""
                })
            }
        } else {
            console.log("QmlBridge not available, audit data cannot be loaded")
        }
    }
    
    function getActionString(actionType) {
        // Convert numeric action type to string
        switch(actionType) {
            case 0: return "Create"
            case 1: return "Read"
            case 2: return "Update"
            case 3: return "Delete"
            case 4: return "Login"
            case 5: return "Logout"
            case 6: return "System"
            default: return "Unknown"
        }
    }
    
    function refreshAuditData() {
        console.log("Refreshing audit data...")
        loadAuditData()
    }
    
    function filterAuditData() {
        console.log("Filtering audit data:", actionFilter.currentText, userFilter.currentText, dateFilter.text)
        
        auditListModel.clear()
        
        if (qmlBridge) {
            var fromDate = dateFilter.text || ""
            var toDate = dateFilter.text || ""
            var userId = userFilter.currentText === "All Users" ? "" : userFilter.currentText
            var action = actionFilter.currentText === "All Actions" ? "" : actionFilter.currentText
            
            var auditData = qmlBridge.getAuditLogs(fromDate, toDate, userId, action)
            
            for (var i = 0; i < auditData.length; i++) {
                var record = auditData[i]
                auditListModel.append({
                    timestamp: record.timestamp || "",
                    userId: record.userId || "",
                    action: getActionString(record.action) || "Unknown",
                    tableName: record.tableName || "",
                    recordId: record.recordId || "",
                    oldValue: record.oldValue || "",
                    newValue: record.newValue || "",
                    description: record.description || ""
                })
            }
        }
    }
    
    function showAuditDetails(index) {
        auditDetailsDialog.currentRecord = auditListModel.get(index)
        auditDetailsDialog.open()
    }
}